﻿
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DBHelper;

namespace ZoneLine
{
    internal class PlcInfoViewModel : ViewModelBase
    {
        #region MyRegion
        private t_Plc _SelectedModel;
        private t_Plc currModelbak;
        #endregion
        public PlcInfoViewModel(t_Plc model)
        {
            if (model == null)
            {
                model = new t_Plc();
            }
            currModelbak = model;
            SelectedModel = currModelbak.Clone<t_Plc>();
            IsAddMode = SelectedModel.ID == 0;
        }

        public override bool Init()
        {
            return true;
        }

        public t_Plc SelectedModel { get => _SelectedModel; set => Set(ref _SelectedModel, value); }

        /// <summary>
        /// 编辑模式
        /// </summary>
        public bool IsAddMode { get; set; } = false;

        #region Command

        #region SaveCmd
        private RelayCommand saveCmd;
        public RelayCommand SaveCmd => saveCmd ?? (saveCmd = new RelayCommand(Save, CanSave));

        private void Save()
        {
            try
            {
                bool rlt = false;
                if (IsAddMode)
                {
                    rlt = DbContext.AddModel(SelectedModel);
                }
                else
                {
                    rlt = DbContext.UpdateModel(SelectedModel, currModelbak);
                }
                ShowMsg(rlt ? "保存成功！" : "保存失败，请查阅Logs！");
            }
            catch (Exception ex)
            {
                ShowMsg("保存失败，请查阅Logs！");
            }
        }

        private bool CanSave()
        {
            return SelectedModel.Validate();
        }
        #endregion

        #endregion
    }
}
